package middleware

import (
	"dev-assistant-backend/internal/consts"
	jwtUtil "dev-assistant-backend/utility/jwt"
	"strings"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

// MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
func MiddlewareJwt(r *ghttp.Request) {

	//exclude apis that do not need jwt
	if r.URL.Path == "/user/login" {
		r.Middleware.Next()
		return
	}
	if r.URL.Path == "/user/create" {
		r.Middleware.Next()
		return
	}

	authorization := r.Header.Get("authorization")
	if authorization == "" {
		authorization = r.Cookie.Get("token").String()
		if authorization == "" {
			r.Response.WriteJson(g.Map{
				"code":    401,
				"message": "jwt is required",
			})
			r.Exit()
		}
	}

	authorization, _ = strings.CutPrefix(authorization, "Bearer ")

	payload, err := jwtUtil.ParseToken(r.Context(), authorization)
	if err != nil {
		g.Log().Line(true).Info(r.Context(), "jwt parse error", "error", err)
		r.Response.WriteJson(g.Map{
			"code":    401,
			"message": "jwt is invalid",
		})
		r.Exit()
	}

	r.SetCtxVar(consts.JwtPayloadKey, payload)

	r.Middleware.Next()
}
